﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Drawing;
using System.Drawing.Imaging;
using System.Web.UI.WebControls;
using System.IO;
using AVCare.LMS.Models;
using AVCare.LMS.Util;
using AVCare.LMS.DataAccess;
using System.Web.Security;

namespace AVCare.LMS.Web.Controllers
{
    public class UserController : Controller
    {
        //
        // GET: /User/

        public ActionResult LoginPartial()
        {
            return View("_loginPartial");
        }

        public ActionResult Login(FormCollection form)
        {
            if (form == null)
            {
                return this.Redirect(Request.UrlReferrer.ToString());
            }
            //检验验证码，
            string validateCode = Request.Cookies["validatecode"].Value;
            if (!validateCode.Equals(form["validatecode"]))
            {
                return Json(LanguageHelper.GetString("error.validatecode"));
            }
            //验证用户名，密码         
            IUserHelper helper = HelperProvider.GetUserHelper();
            User user = helper.GetUser(form["username"]);
            string password = EncryptString2MD5.Encrypt(form["password"]);
            if (user != null && user.Password.Equals(password))
            {
                List<Role> role = helper.GetUserRole(user.ID);
                string roles = string.Join<Role>(",", role);
                FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(1, user.ID, DateTime.Now, DateTime.Now.AddHours(24), false, roles, "/");
                string encryptedTicket = FormsAuthentication.Encrypt(authTicket);
                HttpCookie UserCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
                Response.Cookies.Add(UserCookie);
                Session.Remove("ValidateCode");
                return new EmptyResult();
            }
            return Json(LanguageHelper.GetString("error.invalidated"));

        }

        public ActionResult Logout()
        {
            FormsAuthentication.SignOut();
            return Redirect(Request.UrlReferrer.ToString());
        }
    }
}
